package com.thinkgem.jeesite.modules.ems.web;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.ems.entity.EmsCourse;
import com.thinkgem.jeesite.modules.ems.entity.EmsDept;
import com.thinkgem.jeesite.modules.ems.entity.EmsMajor;
import com.thinkgem.jeesite.modules.ems.entity.EmsTerm;
import com.thinkgem.jeesite.modules.ems.service.EmsCourseService;
import com.thinkgem.jeesite.modules.ems.service.EmsDeptService;
import com.thinkgem.jeesite.modules.ems.service.EmsMajorService;
import com.thinkgem.jeesite.modules.ems.service.EmsTermService;

/**
 * 班级Controller
 * @author zad
 * @version 2018-01-25
 */
@Controller
@RequestMapping(value = "${adminPath}/ems/emsCourse")
public class EmsCourseController extends BaseController {

	@Autowired
	private EmsCourseService emsCourseService;
	
	@Autowired
	private EmsTermService emsTermService;
	
	@Autowired
	private EmsDeptService emsDeptService;
	
	@Autowired
	private EmsMajorService emsMajorService;
	
	@Autowired
	private EmsMajorService emsTeacherService;
	
	@Autowired
	private EmsMajorService emsClassroomService;
	
	@ModelAttribute
	public EmsCourse get(@RequestParam(required=false) String id) {
		EmsCourse entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = emsCourseService.get(id);
		}
		if (entity == null){
			entity = new EmsCourse();
		}
		return entity;
	}
	
	@RequiresPermissions("ems:emsCourse:view")
	@RequestMapping(value = {"list", ""})
	public String list(EmsCourse emsCourse, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		System.out.println("-----------------------" + request.getContextPath());
		
		List<EmsTerm> terms = this.emsTermService.findList(null);
		model.addAttribute("terms", terms);
		
		// add by zad 2018-01-26
		List<EmsDept> depts = this.emsDeptService.findList(null);
		model.addAttribute("depts", depts);
		
		EmsMajor major = new EmsMajor();
		// 当前台已选则区域时，查询的专业应该基于此区域
		if(null != emsCourse.getMajor() && null != emsCourse.getMajor().getDept() && StringUtils.isNotBlank(emsCourse.getMajor().getDept().getId()))
		{
			major.setDept(emsCourse.getMajor().getDept());
		}
		else
		{
			if(null != depts && depts.size() > 0)
			{
				major.setDept(depts.get(0));
			}
		}
		List<EmsMajor> majors = this.emsMajorService.findList(major);
		model.addAttribute("majors", majors);
		
		Page<EmsCourse> page = emsCourseService.findPage(new Page<EmsCourse>(request, response), emsCourse); 
		model.addAttribute("page", page);
		return "modules/ems/emsCourseList";
	}
	
	// add by zad 2018-02-02 用于课程查询
	@RequiresPermissions("ems:emsCourse:view")
	@RequestMapping(value = {"select"})
	public String select(EmsCourse emsCourse, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		List<EmsTerm> terms = this.emsTermService.findList(null);
		model.addAttribute("terms", terms);
		
		// add by zad 2018-01-26
		List<EmsDept> depts = this.emsDeptService.findList(null);
		model.addAttribute("depts", depts);
		
		EmsMajor major = new EmsMajor();
		// 当前台已选则区域时，查询的专业应该基于此区域
		if(null != emsCourse.getMajor() && null != emsCourse.getMajor().getDept() && StringUtils.isNotBlank(emsCourse.getMajor().getDept().getId()))
		{
			major.setDept(emsCourse.getMajor().getDept());
		}
		else
		{
			if(null != depts && depts.size() > 0)
			{
				major.setDept(depts.get(0));
			}
		}
		List<EmsMajor> majors = this.emsMajorService.findList(major);
		model.addAttribute("majors", majors);
		
		Page<EmsCourse> page = emsCourseService.findPage(new Page<EmsCourse>(request, response), emsCourse); 
		model.addAttribute("page", page);
		return "modules/ems/emsCourseSelect";
	}
	
	@RequiresPermissions("ems:emsCourse:view")
	@RequestMapping(value = {"copy"})
	public String copy(EmsCourse emsCourse, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		List<EmsTerm> terms = this.emsTermService.findList(null);
		model.addAttribute("terms", terms);
		if(null != emsCourse && null != emsCourse.getTerm() && StringUtils.isNotBlank(emsCourse.getTerm().getId()))
		{
			model.addAttribute("termId", emsCourse.getTerm().getId());
		}
		Page<EmsCourse> page = emsCourseService.findPage(new Page<EmsCourse>(request, response), emsCourse); 
		model.addAttribute("page", page);
		return "modules/ems/emsCourseCopy";
	}
	
	@RequiresPermissions("ems:emsCourse:edit")
	@RequestMapping(value = {"copyCourse"})
	public String copyCourse(String termId,String termName,String newTerm, HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes) {
		
		List<EmsTerm> terms = this.emsTermService.findList(null);
		model.addAttribute("terms", terms);
		
		// 课程复制
		Map<String,String> param = new HashMap<String, String>();
		param.put("termId", termId);
		param.put("termName", termName);
		param.put("newTerm", newTerm);
		int rows = this.emsCourseService.copyCourse(param);
		
		if(rows > 0)
		{
			addMessage(redirectAttributes, "学期复制成功");
			model.addAttribute("rs", "yes");
		}
		else
		{
			addMessage(redirectAttributes, "所选学期未找到课程");
			model.addAttribute("rs", "no");
		}
		
		model.addAttribute("termId", newTerm);
		
		EmsCourse emsCourse = new EmsCourse();
		EmsTerm term = new EmsTerm();
		term.setId(newTerm);
		emsCourse.setTerm(term);
		Page<EmsCourse> page = emsCourseService.findPage(new Page<EmsCourse>(request, response), emsCourse); 
		model.addAttribute("page", page);
		return "modules/ems/emsCourseCopy";
		
		// return "redirect:"+Global.getAdminPath()+"/ems/emsCourse/copy?repage";
	}

	@RequiresPermissions("ems:emsCourse:view")
	@RequestMapping(value = "form")
	public String form(EmsCourse emsCourse, Model model) {
		
		// add by zad 2018-01-26
		List<EmsTerm> terms = this.emsTermService.findList(null);
		model.addAttribute("terms", terms);
		
		List<EmsDept> depts = this.emsDeptService.findList(null);
		model.addAttribute("depts", depts);
		
		// 查询专业时，默认为一个部门的专业
		/*EmsMajor major = new EmsMajor();
		if(null != depts && depts.size() > 0)
		{
			major.setDept(depts.get(0));
		}*/
		
		
		List<EmsMajor> majors = null;
		// 修改时，查询所有已选部门下的专业
		if(null != emsCourse && !StringUtils.isBlank(emsCourse.getId()))
		{
			emsCourse.getMajor().setName(null);
			majors = this.emsMajorService.findList(emsCourse.getMajor());
		}else
		{
			EmsMajor major = new EmsMajor();
			if(null != depts && depts.size() > 0)
			{
				major.setDept(depts.get(0));
			}
			majors = this.emsMajorService.findList(major);
		}
		
		model.addAttribute("majors", majors);
		
		// List<EmsMajor> majors = this.emsMajorService.findList(null);
		
		
		model.addAttribute("emsCourse", emsCourse);
		return "modules/ems/emsCourseForm";
	}

	@RequiresPermissions("ems:emsCourse:edit")
	@RequestMapping(value = "save")
	public String save(HttpServletRequest request, HttpServletResponse response, EmsCourse emsCourse, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, emsCourse)){
			return form(emsCourse, model);
		}
		
		
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 
		 String dateStr = DateUtils.getDate("yyyy/MM/dd");
		 
	     /** 构建文件保存的目录* */
	      String logoPathDir = "userfiles/1/images/cms/course/logo/" + dateStr + "/";
	      /** 得到文件保存目录的真实路径* */
	      /*String logoRealPathDir = request.getSession().getServletContext()
	              .getRealPath(logoPathDir);*/
	      String logoRealPathDir = Global.getUserfilesBaseDir()+logoPathDir;
	      
	      /** 根据真实路径创建目录* */
	      File logoSaveFile = new File(logoRealPathDir);
	      if (!logoSaveFile.exists())
	      {
	          logoSaveFile.mkdirs();
	      }
	      /** 页面控件的文件流* */
	      MultipartFile multipartFile = multipartRequest.getFile("file");
	      if(multipartFile.getSize() > 0){
	    	  /** 获取文件的后缀* */
	          //String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
	                  
	          /** 使用UUID生成文件名称* */
	          //String logImageName = UUID.randomUUID().toString() + suffix;// 构建文件名称
	          String logImageName = multipartFile.getOriginalFilename();// 构建文件名称
	                  
	          /** 拼成完整的文件保存路径加文件* */
	          String fileName = logoRealPathDir + File.separator + logImageName;
	          File file = new File(fileName);
	          try {
	              multipartFile.transferTo(file);
	          } catch (IllegalStateException e) {
	              e.printStackTrace();
	          } catch (IOException e) {
	              e.printStackTrace();
	          }
	          emsCourse.setLogo(request.getContextPath() + "/"+logoPathDir+logImageName);
	      }
	      
	      
	      
		
		emsCourseService.save(emsCourse);
		addMessage(redirectAttributes, "保存班级成功");
		return "redirect:"+Global.getAdminPath()+"/ems/emsCourse/?repage";
	}
	
	@RequiresPermissions("ems:emsCourse:edit")
	@RequestMapping(value = "delete")
	public String delete(EmsCourse emsCourse, RedirectAttributes redirectAttributes) {
		emsCourseService.delete(emsCourse);
		addMessage(redirectAttributes, "删除班级成功");
		return "redirect:"+Global.getAdminPath()+"/ems/emsCourse/?repage";
	}

}